package top.ply.manageservice.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import top.ply.common_unit.entity.RespEntity;
import top.ply.common_unit.global_resp.RespUtil;
import top.ply.manageservice.pojo.Manager;
import top.ply.manageservice.service.ManagerService;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    ManagerService managerService;

    @Autowired
    TokenAuthFilter tokenAuthFilter;

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable()
                // 关闭会话存储，适应集群搭建
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/manager/login").permitAll()
                .antMatchers("/manager/add").hasRole("admin")
                .anyRequest().authenticated();
        http.addFilterBefore(tokenAuthFilter, UsernamePasswordAuthenticationFilter.class);
        // 禁用缓存
        http.headers().cacheControl();
    }

    /**
     * 自定义安全拦截器
     * 基本原理是：Spring Security通过一级一级的Filter来确定一个请求是否具有访问某一个接口的权现
     * 在UsernamePasswordAuthenticationFilter中通过请求参数中的用户名和密码进行校验，
     * 然后生成UsernamePasswordAuthenticationToken对象注入进Spring Security上下文你中
     * 之后SecurityContextHolder.getContext().getAuthentication()不再为null，从而校验通过
     *
     * 要实现自定义的token校验策略，可以在UsernamePasswordAuthenticationFilter之前添加一个过滤器
     * 这个过滤器校验请求头中的授权字段，校验成功后生成UsernamePasswordAuthenticationToken对象，
     * 在其构造方法中，调用父类的setAuthenticated(true);方法来指定授权成功，以此覆盖SpringSecurity的默认校验行为
     *
     * (其实添加在UsernamePasswordAuthenticationFilter之前不是必须的，只要添加在FilterChain中即可完成自定义授权)
     */
    @Component
    public class TokenAuthFilter extends OncePerRequestFilter {

        static final String tokenHeader = "Authorization";

        @Override
        protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain filterChain) throws ServletException, IOException {
            String token = req.getHeader(tokenHeader);
            if (token != null) {
                if (managerService.verifyToken(token)) {
                    Manager manager = managerService.getManagerFromToken(token);
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(manager, null, manager.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
            filterChain.doFilter(req, resp);
        }
    }
}
